//给你单链表的头节点 head ，请你反转链表，并返回反转后的链表。
// 
// 
// 
//
// 示例 1： 
//
// 
//输入：head = [1,2,3,4,5]
//输出：[5,4,3,2,1]
// 
//
// 示例 2： 
//
// 
//输入：head = [1,2]
//输出：[2,1]
// 
//
// 示例 3： 
//
// 
//输入：head = []
//输出：[]
// 
//
// 
//
// 提示： 
//
// 
// 链表中节点的数目范围是 [0, 5000] 
// -5000 <= Node.val <= 5000 
// 
//
// 
//
// 进阶：链表可以选用迭代或递归方式完成反转。你能否用两种方法解决这道题？ 
// 
// 
// Related Topics 递归 链表 
// 👍 2150 👎 0

package leetcode.editor.cn;

import java.util.List;

/**
 * [206]反转链表
 */
public class ReverseLinkedList {
    public static void main(String[] args) {
        Solution solution = new ReverseLinkedList().new Solution();
        ListNode head = new ReverseLinkedList().new ListNode();
        head.val = 1;

        ListNode node1 = new ReverseLinkedList().new ListNode();
        node1.val = 2;
        head.next = node1;

        ListNode node2 = new ReverseLinkedList().new ListNode();
        node2.val = 3;
        node1.next = node2;

//        ListNode node3 = new ReverseLinkedList().new ListNode();
//        node3.val = 4;
//        node2.next = node3;
//
//        ListNode node4 = new ReverseLinkedList().new ListNode();
//        node4.val = 5;
//        node3.next = node4;

        ListNode newHead = solution.reverseList(head);
        System.out.println(newHead);
    }
    //leetcode submit region begin(Prohibit modification and deletion)
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */

public class ListNode {
    int val;
    ListNode next;
    ListNode() {}
    ListNode(int val) { this.val = val; }
    ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}

class Solution {
    // 个人
    public ListNode reverseList2(ListNode head) {
        if (head == null) {
            return null;
        }
        ListNode newNode = head;
        ListNode nowNode = head.next;
        head.next = null;
        ListNode temp;
        while (nowNode != null) {
            temp = nowNode;
            nowNode = nowNode.next;
            temp.next = newNode;
            newNode = temp;
        }
        return newNode;
    }

    // 优化
    public ListNode reverseList3(ListNode head) {
        ListNode newNode = null;
        ListNode curr = head;
        ListNode temp;
        while (curr != null) {
            temp = curr.next;
            curr.next = newNode;
            newNode = curr;
            curr = temp;
        }
        return newNode;
    }

    // 还可以递归实现
    public ListNode reverseList(ListNode head) {
        return reverse(null, head);
    }

    private ListNode reverse(ListNode pre, ListNode cur) {
        if (cur == null) {
            return pre;
        }
        ListNode next = cur.next;
        cur.next = pre;
        return reverse(cur, next);
    }
}
//leetcode submit region end(Prohibit modification and deletion)

}